#coding=utf-8
import web
import json
import model
import os


urls = (
    '/','Emails',
    '/emails','Emails',
    '/trash','Trash',
    '/settings','Settings',
    '/getemails','getEmails',
    '/getdeletedemails','getDeletedEmails',
    '/deletemails','deleteMails',
    '/starmails','starMails', 
    '/unstarmails','unstarMails', 
    '/readheader','readHeader',         
)

#layout.html重用页面
render = web.template.render('templates',base='layout')

        
class Emails:
    def GET(self):
        """获取收件箱邮件"""
        return render.emails()

class Trash:
    def GET(self):
        """获取回收站邮件"""
        return render.trash()
        
class Settings:
    def GET(self):
        """获取设置"""
        return render.settings()
               
class getEmails:
    def POST(self):
        """get emails in json format"""
        emails = model.get_emails() 
        emailjson = getmails(emails)
        #设置返回数据为json格式
        web.header('content-type','text/json')
        return json.dumps(emailjson)
        
class getDeletedEmails:
    def POST(self):
        """get deleted emails in json format"""
        emails = model.get_deletedemails() 
        emailjson = getmails(emails)
        web.header('content-type','text/json')
        return json.dumps(emailjson)
            
        
class deleteMails:
    def POST(self):
        """delete emails by mailid"""
        data = web.data()
        mailids=[]
        for kvstr in data.split('&'):
            mailids.append(kvstr.split('=')[1])
        for id in mailids:
            model.delete_email(id)
        web.header('content-type','text/json')
        return json.dumps('ok')
        
class starMails:
    def POST(self):
        """star emails by mailid"""
        data = web.data()
        mailids=[]
        for kvstr in data.split('&'):
            mailids.append(kvstr.split('=')[1]) 
        for id in mailids:
            model.star_email(id)
        web.header('content-type','text/json')
        return json.dumps('ok')
        
class unstarMails:
    def POST(self):
        """unstar emails by mailid"""
        data = web.data()
        mailids=[]
        for kvstr in data.split('&'):
            mailids.append(kvstr.split('=')[1]) 
        for id in mailids:
            model.unstar_email(id)
        web.header('content-type','text/json')
        return json.dumps('ok')

        
class readHeader:
    def POST(self):
        """read email header by mailid"""
        data = web.data()
        contents = []
        files=[]
        mailids=[]
        filepath = ''
        for kvstr in data.split('&'):
            mailids.append(kvstr.split('=')[1])
        for id in mailids:
            emails = model.get_emailpath(id) 
            for email in emails:
                filepath = email.filedir
                file = os.path.join(filepath, id)
                files.append(file)
        for file in files:
            content = readfile(file)
            contents.append(content)
        Header = contents[0]#暂时只支持查看一个文件
        web.header('content-type','text/json')
        return json.dumps(Header)

def getmails(data):
    emails = data
    emailjson = {}
    rows = []
    for email in emails:
    #mailid,sender,subject,receivetime,filesize
        cell = {}
        row = {}
        cell['mailid'] = email.mailid
        cell['star'] = email.star and 'true' or 'false'
        cell['sender'] = email.sender
        cell['subject'] = email.subject
        cell['receivetime'] = email.receivetime.strftime("%m-%d %H:%M")
        cell['filesize'] = readablesize(email.filesize)
        row['id'] = email.mailid
        row['cell'] = cell
        rows.append(row)
    emailjson['page']=1
    emailjson['total']=len(emails)
    emailjson['rows']=rows
    return emailjson        
        
def readablesize(filesize):
    """将原先以bytes为单位的文件大小转为以K 或者M bytes为单位"""
    size = int(filesize)
    sizestr = str(size)
    if size > 0 and size < 1024:
        sizestr = str(size)
    elif size >= 1024 and size < 1024*1024:
        sizestr = str(size/1024)+"K"
    elif size >=1024*1024 and size < 1024*1024*1024:
        sizestr = str(size/1024/1024)+"M"
    else:
        sizestr = "xG"#太大不去考虑，也许会过滤掉
    return sizestr
    
def readfile(file):
    """读取文件正文"""
    f = open(str(file),'rb')
    try:
        content = f.read()
    finally:
        f.close()
    return content
        
app = web.application(urls, globals())

if __name__ == '__main__':
    app.run()